# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: jhkim

import logging

from absl import app, flags

import coin.strategy.mm.tool.archive_base as abase
import coin.strategy.mm.tool.taker_ratio2 as tr2
import coin.strategy.mm.tool.orderstat_intraday as ointra

from coin.experimental.jhkim.oglog_hack_history_reader import get_run_history_df_from_file_hack
from coin.base.param_util import split_string
from xunkemgmt_client.client.util.query_util import (
    query_strategies, query_applications)


def main(_):
  strat_sels = query_strategies(strategy_names=split_string(flags.FLAGS.strategy_name), as_proto=True)
  acdf = query_applications(strategy_ids=[strat.strategy_id for strat in strat_sels])

  rhdf = get_run_history_df_from_file_hack()

  rhdf["owner"] = rhdf["account"]

  allinfo_df = acdf.merge(rhdf, on=['exchange', 'market_type', 'owner'])
  assert len(allinfo_df) > 0, acdf

  trading_dates = abase.get_trading_dates(flags.FLAGS.trading_date)

  if flags.FLAGS.module == 'taker_ratio2':
    for trading_date in trading_dates:
      seldf = allinfo_df.loc[allinfo_df['datestr'].astype(str) == trading_date.strftime("%Y%m%d")]
      for _, orderlogrow in seldf.iterrows():
        # note that indirect parameter passing is hack.. will fix in the future..
        flags.FLAGS.orderlog_machine = orderlogrow['machine']
        flags.FLAGS.exchange = orderlogrow['exchange']
        flags.FLAGS.market_type = orderlogrow['market_type']
        flags.FLAGS.owner = orderlogrow['owner']
        flags.FLAGS.trading_date = trading_date.strftime("%Y%m%d")

        if flags.FLAGS.symbol is None:
          all_symbols = abase.get_all_symbols_from_og_archive_from_flags()
        else:
          all_symbols = [flags.FLAGS.symbol]

        for each_symbol in all_symbols:
          # don't like it.. but it's tr2's fault..
          flags.FLAGS.symbol = each_symbol
          tr2.launch_date(trading_date, postfix=flags.FLAGS.strategy_name)

  elif flags.FLAGS.module == 'orderstat_intraday':
    for trading_date in trading_dates:
      seldf = allinfo_df.loc[allinfo_df['datestr'].astype(str) == trading_date.strftime("%Y%m%d")]
      for _, orderlogrow in seldf.iterrows():
        # note that indirect parameter passing is hack.. will fix in the future..
        flags.FLAGS.orderlog_machine = orderlogrow['machine']
        flags.FLAGS.exchange = orderlogrow['exchange']
        flags.FLAGS.market_type = orderlogrow['market_type']
        flags.FLAGS.owner = orderlogrow['owner']
        flags.FLAGS.trading_date = trading_date.strftime("%Y%m%d")

        if flags.FLAGS.symbol is None:
          all_symbols = abase.get_all_symbols_from_og_archive_from_flags()
        else:
          all_symbols = [flags.FLAGS.symbol]

        for each_symbol in all_symbols:
          flags.FLAGS.symbol = each_symbol
          ointra.launch_date(trading_date, postfix=flags.FLAGS.strategy_name)


# ./pyrunner coin/strategy/mm/tool/strategy_analysis.py --strategy_name=huobi_futures_quarter --use_feed_cache=True --trading_date=20190701-20190730
if __name__ == '__main__':
  abase.define_base_flags()
  abase.define_order_archive_flags()
  abase.define_feed_archive_flags()

  flags.FLAGS.feed_machine = 'feed-01.ap-northeast-1.aws'

  flags.DEFINE_string('module', 'taker_ratio2', 'module name')

  flags.DEFINE_string('symbol', None, 'symbol str')

  logging.basicConfig(level='DEBUG', format='%(levelname)8s %(asctime)s %(name)s] %(message)s')
  app.run(main)
